<?php

namespace app\common\command\task;

use app\common\exception\BusinessException;
use app\common\model\SystemException;
use PHPMailer\PHPMailer\Exception;

/**
 * SendExceptionMessage
 */
class SendExceptionMessage
{
    /**
     * invoke
     * @throws
     */
    public function invoke()
    {
        // 查询条件
        $where = [
            ['status', '=', 1]
        ];
        $list = app(SystemException::class)->where($where)->select();
        foreach ($list as $item) {
            $this->executeItem($item);
        }
    }

    /**
     * @param $item
     * @return void
     * @throws BusinessException
     */
    private function executeItem($item)
    {
        // 提取参数
        $address = '392223903@qq.com';
        $subject = '系统异常，异常编号:' . $item['id'];
        $message = $this->format($item);

        // 发送邮箱
        $sendStatus = 2;
        try {
            send_email($address, $subject, $message);
        } catch (Exception|BusinessException $e) {
            $sendStatus = 3;
        }

        // 更新数据
        $saveData = [
            'status' => $sendStatus,
        ];
        $where = [['id', '=', $item['id']]];
        $isUpdate = app(SystemException::class)->where($where)->update($saveData);
        if ($isUpdate === false) {
            throw new BusinessException('更新失败');
        }
    }

    /**
     * format
     * @param $item
     * @return string
     */
    private function format($item): string
    {
        return 'req:' . $item['req'] . PHP_EOL . PHP_EOL . 'con:' . PHP_EOL . PHP_EOL . $item['con'];
    }
}
